<?php

use models\Business\Exchange;
use Yaf\Registry;
use models\Business\Finance;
use models\Business\Order;
use models\Exception\Business\TurnoverException;


class FinanceController extends ApiBaseController
{
    /**
     * @SWG\Post(
     *     path="/v3/finance/withdraw",
     *     tags={"财务模块"},
     *     summary="提现",
     *     description="
     * account_id 必须参数 提现账号编号 v3/account/list接口获取
     * amount 必须参数 要提现的金额
     * paypassword 必须参数 支付密码",
     *     @SWG\Parameter(
     *          name="Authorization",
     *          description="Authorization 登录接口返回的jwt字段的值",
     *          in="header",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Parameter(
     *          name="secret",
     *          description="加密字符串",
     *          in="formData",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Response(
     *         response="201",
     *         description="请求成功"
     *     ),
     *     @SWG\Response(
     *         response="422",
     *         description="创建失败"
     *     ),
     *     @SWG\Response(
     *         response="400",
     *         description="签名不存在或无效签名"
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="jwt无效或过期，需要登录"
     *     ),
     *     @SWG\Response(
     *         response="403",
     *         description="无权访问"
     *     ),
     *     @SWG\Response(
     *         response="404",
     *         description="找不到数据"
     *     )
     * )
     */
    public function withdrawAction() {
        $parameters = Registry::get('parameters');
        $parameters['type'] = 5;

        Finance::withdraw($parameters);

        return $this->_responseJson(new stdClass(), '000', TurnoverException::WITHDRAW_SUCCESS);
    }

    /**
     * @SWG\Post(
     *     path="/v3/finance/exchange",
     *     tags={"财务模块"},
     *     summary="积分转余额",
     *     description="
     * type 必须参数 类型 固定值: 3
     * amount 必须参数 要专成余额的金币数量，具体的返回值需要通过finance/exchangelist接口type=0返回的id",
     *     @SWG\Parameter(
     *          name="Authorization",
     *          description="Authorization 登录接口返回的jwt字段的值",
     *          in="header",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Parameter(
     *          name="secret",
     *          description="加密字符串",
     *          in="formData",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Response(
     *         response="201",
     *         description="请求成功"
     *     ),
     *     @SWG\Response(
     *         response="422",
     *         description="创建失败"
     *     ),
     *     @SWG\Response(
     *         response="400",
     *         description="签名不存在或无效签名"
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="jwt无效或过期，需要登录"
     *     ),
     *     @SWG\Response(
     *         response="403",
     *         description="无权访问"
     *     ),
     *     @SWG\Response(
     *         response="404",
     *         description="找不到数据"
     *     )
     * )
     */
    public function exchangeAction() {
        $parameters = Registry::get('parameters');

        $exchange = Exchange::getExchange($parameters['amount']);
        $parameters['amount'] = $exchange['price'];
        $parameters['exchange'] = $exchange['exchange'];

        Finance::exchange($parameters);

        // 增加金豆兑换余额商品的销量
        Exchange::editExchange(['sales' => $exchange['sales'] + 1, 'id' => $exchange['id'], 'from_api' => true]);

        return $this->_responseJson(new stdClass(), '000', TurnoverException::EXCHANGE_SUCCESS);
    }

    /**
     * @SWG\Get(
     *     path="/v3/finance/withdrawrequest",
     *     tags={"财务模块"},
     *     summary="获取当前登陆用户的提现申请列表接口",
     *     description="
     * page 必须参数 页码
     * page_size 必须参数 每页显示条数
     * sort 必须参数 排序方式 可选值:desc降序、asc生序
     * order 必须参数 排序字段 固定值 id
     * type 必须参数 类型 固定值：5",
     *     @SWG\Parameter(
     *          name="Authorization",
     *          description="Authorization 登录接口返回的jwt字段的值",
     *          in="header",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Parameter(
     *          name="secret",
     *          description="加密字符串",
     *          in="query",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Response(
     *         response="200",
     *         description="请求成功",
     *         @SWG\Schema(type="object", ref="#/definitions/turnoverListData")
     *     ),
     *     @SWG\Response(
     *         response="400",
     *         description="签名不存在或无效签名"
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="jwt无效或过期，需要登录"
     *     ),
     *     @SWG\Response(
     *         response="403",
     *         description="无权访问"
     *     ),
     *     @SWG\Response(
     *         response="404",
     *         description="找不到数据"
     *     )
     * )
     */
    public function withdrawListAction() {
        $parameters = Registry::get('parameters');

        $withdraw_list = Finance::getWithdrawList($parameters);

        return $this->_responseJson($withdraw_list);
    }

    /**
     * @SWG\Get(
     *     path="/v3/finance/turnover",
     *     tags={"财务模块"},
     *     summary="获取流水记录",
     *     description="
     * page 必须参数 页码
     * page_size 必须参数 每页显示条数
     * sort 必须参数 排序方式 可选值:desc降序、asc生序
     * order 必须参数 排序字段 固定值 id
     * type 必须参数 类型 finance/turnovertype接口返回的id",
     *     @SWG\Parameter(
     *          name="Authorization",
     *          description="Authorization 登录接口返回的jwt字段的值",
     *          in="header",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Parameter(
     *          name="secret",
     *          description="加密字符串",
     *          in="query",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Response(
     *         response="200",
     *         description="请求成功",
     *         @SWG\Schema(type="object", ref="#/definitions/turnoverListData")
     *     ),
     *     @SWG\Response(
     *         response="400",
     *         description="签名不存在或无效签名"
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="jwt无效或过期，需要登录"
     *     ),
     *     @SWG\Response(
     *         response="403",
     *         description="无权访问"
     *     ),
     *     @SWG\Response(
     *         response="404",
     *         description="找不到数据"
     *     )
     * )
     */
    public function turnoverAction() {
        $parameters = Registry::get('parameters');

        if (in_array($parameters['type'], [9, 10])) {
            $type_arr = array_column(Finance::INTEGRAL_TURNOVER_TYPE, 'name', 'id');

            $parameters['member_id'] = Registry::get('jwt_info')->id;
            $parameters['failure_stats'] = $parameters['type'] == 7 ? 'toBeContinued' : 'cancel';
            $parameters['order'] = 'created_at';
            $type_name = $type_arr[$parameters['type']];
//            exit(json_encode($type_arr));
            $parameters['type'] = 0;
            $order = Order::getOrderList($parameters);

            $system = \models\Business\System::getSystemInfo(1);
            $rebate_rate = $system['rebate_rate'];
//            $parent_rebate_rate = $system['parent_rate'];
//            $grand_parent_rebate_rate = $system['sub_rate'];

            $turnover = ['data' => [], 'meta' => $order['meta']];

            foreach ($order['data'] as $order_info) {
                array_push($turnover['data'], [
                    'id' => $order_info['sn'],
                    'member_id' => $order_info['fail_member_id'],
                    'remark' => '拼单赠送',
                    'product_id' => $order_info['product_info']['product_id'],
                    'product_title' => $order_info['product_info']['title'],
                    'product_img' => $order_info['product_info']['img_url'],
                    'account_id' => 0,
                    'currency' => 0.00,
                    'amount' => $order_info['amount'],
                    'type' => $type_name,
                    'type_name' => $type_name,
                    'created_at' => $order_info['created_at'],
                    'updated_at' => $order_info['updated_at'],
                    'updated_by' => 0
                ]);
            }
        } else {
            $turnover = Finance::getWithdrawList($parameters);
            foreach ($turnover['data'] as $idx => $turnover_info) {
                if(in_array($turnover_info['type'], [0, 2])){
                    $turnover['data'][$idx]['amount'] =sprintf('%.0f', $turnover_info['amount']);
                    $turnover['data'][$idx]['currency'] =sprintf('%.0f', $turnover_info['currency']);
                    $turnover['data'][$idx]['remain'] =sprintf('%.0f', $turnover_info['remain']);
                }
                $turnover['data'][$idx]['type_name'] = (in_array($turnover_info['type'], [4, 5]) ? '提现' :
                    ($turnover_info['type'] == 3 ? '兑换' :
                        ($turnover_info['type'] == 0 ? '获得记录' :
                            ($turnover_info['type'] == 1 ? '兑换' : '其他'))));

                $turnover['data'][$idx]['remarks']=$turnover_info['remark'];
                if($turnover_info['type']==0){
                    $arr=explode('|',$turnover_info['remark']);
                    if(count($arr)==2){
                        $turnover['data'][$idx]['remark']=explode('|',$turnover_info['remark'])[0];
                        $turnover['data'][$idx]['remarks']=explode('|',$turnover_info['remark'])[1];
                    }

                }
            }
        }

        return $this->_responseJson($turnover);
    }

    /**
     * @SWG\Get(
     *     path="/v3/finance/turnovertype",
     *     tags={"财务模块"},
     *     summary="获取流水记录",
     *     description="
     * page 必须参数 页码
     * page_size 必须参数 每页显示条数 固定值: 999
     * sort 必须参数 排序方式 固定值: asc
     * order 必须参数 排序字段 固定值 id
     * type 必须参数 类型 可选值: 0为获取金豆流水类型，1为获取余额流水类型",
     *     @SWG\Parameter(
     *          name="Authorization",
     *          description="Authorization 登录接口返回的jwt字段的值",
     *          in="header",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Parameter(
     *          name="secret",
     *          description="加密字符串",
     *          in="query",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Response(
     *         response="200",
     *         description="请求成功",
     *         @SWG\Schema(type="object", ref="#/definitions/turnovertypeListData")
     *     ),
     *     @SWG\Response(
     *         response="400",
     *         description="签名不存在或无效签名"
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="jwt无效或过期，需要登录"
     *     ),
     *     @SWG\Response(
     *         response="403",
     *         description="无权访问"
     *     ),
     *     @SWG\Response(
     *         response="404",
     *         description="找不到数据"
     *     )
     * )
     */
    public function turnoverTypeAction() {
        $parameters = Registry::get('parameters');
        if ($parameters['type'] == 0) {
            $type = Finance::INTEGRAL_TURNOVER_TYPE;
        } else {
            $type = Finance::BALANCE_TURNOVER_TYPE;
        }
        array_multisort(array_column($type, 'key'), SORT_ASC, $type);
        return $this->_responseJson(['data' => $type]);
    }

    /**
     * @SWG\Get(
     *     path="/v3/finance/exchangelist",
     *     tags={"财务模块"},
     *     summary="获取金豆兑换余额商品列表",
     *     description="
     * page 必须参数 页码
     * page_size 必须参数 每页显示条数
     * sort 必须参数 排序方式 可选值:desc降序、asc生序
     * order 必须参数 排序字段 固定值 id
     * type 必须参数 类型 固定值：0",
     *     @SWG\Parameter(
     *          name="Authorization",
     *          description="Authorization 登录接口返回的jwt字段的值",
     *          in="header",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Parameter(
     *          name="secret",
     *          description="加密字符串",
     *          in="query",
     *          required=true,
     *          type="string"
     *     ),
     *     @SWG\Response(
     *         response="200",
     *         description="请求成功",
     *         @SWG\Schema(type="object", ref="#/definitions/integralproductListData")
     *     ),
     *     @SWG\Response(
     *         response="400",
     *         description="签名不存在或无效签名"
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="jwt无效或过期，需要登录"
     *     ),
     *     @SWG\Response(
     *         response="403",
     *         description="无权访问"
     *     ),
     *     @SWG\Response(
     *         response="404",
     *         description="找不到数据"
     *     )
     * )
     */
    public function exchangeListAction() {
        $parameters = Registry::get('parameters');
        $parameters['stats'] = 1;

        $exchange = Exchange::getExchangeList($parameters);

        return $this->_responseJson($exchange);
    }
}
